import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import {config} from '../../../shared/smartadmin.config';

interface QueryForm {
	companyId: String,
	dateType: String,
	startTime: String,
	endTime: String,
	loadingTimeType: String,
	unLoadingTimeType: String,
	deviceId: String,
	useTypeL2: String,
	sortType: String,
	sortTypeNameArr: Array<String>,
	searchKey: String,
	startTransportation: any,
	endTransportation: any,
	loadingAddressId: String,
	unloadAddressId: String,
	loadingAddressPId: String,
	loadingAddressCId: String,
	unloadAddressPId: String,
	unloadAddressCId: String
}

interface Statistics {
	allWeight: String,
	allMileage: String,
	allTime: String,
	allCarNum: String,
	allDaiCarNum: String,
	allSanCarNum: String,
	avgWeightByTime: String,
	avgMileageByTime: String,
	avgCarByTime: String,
	avgWeightByCar: String,
	avgMileageByCar: String
}

declare var $: any;
declare var BMap: any;
declare var BMapLib: any;
declare var echarts: any;
declare var toMapPoint: any;
declare var layui: any;
declare var xmSelectCan: any;
@Component({
  selector: 'sa-task-management',
  templateUrl: './task-management.component.html',
  styleUrls:['./task-management.css']
})
export class TaskManagementComponent implements OnInit {
	statisticsForm = {} as Statistics
	queryForm: QueryForm = {
		companyId: '',
		dateType: '1',
		startTime: '',
		endTime: '',
		loadingTimeType: '',
		unLoadingTimeType: '',
		deviceId: '',
		useTypeL2: '',
		sortType: '',
		sortTypeNameArr: [],
		searchKey: '',
		startTransportation: '',
		endTransportation: '',
		loadingAddressId: '',
		unloadAddressId: '',
		loadingAddressPId: '',
		loadingAddressCId: '',
		unloadAddressPId: '',
		unloadAddressCId: ''
	}
	currentLoadingAddressIdObject = []
	currentUnloadAddressIdObject = []
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	carList:any[] = [];
	companyId:string = '';
	companyList = [];
	deviceId:string = '';//设备ID
	carNumber:string = '';
	startTime:string = '';//开始时间
	endTime:string = '';//结束时间
	btnNum:string = 'all';
	allData:string = '';//数据分类总数
	normalData:string = '';//数据分类正常
	abnormalData:string = '';//数据分类异常
	flag:boolean = false;//记录弹层的显示和隐藏
	isloading:boolean = false;//判断数据是否除以加载中
	activeSelected:string = ''; //row高亮

	mapCantonName:string = '';//行政区域名
	mapCarNumber:string = '';
	mapDeviceId:string = '';
	mapStartTime:string = '';
	mapEndTime:string = '';
	baiduMap:any; //实例化地图对象
	trackData:any[] = [];//轨迹路线数据
	carMoveCanvasLayer:any;//移动折线对应地图添加点的,
	boundaryRegion:any;//行政边界区域构造器
	areaPly:any;//行政边界区域的覆盖图形
	isEnter:boolean = true;//默认选中进入特价区域
	inTimeArr:any[] = [];//存储进入边界的时间,对应outTimeArr离开边界的时间
	outTimeArr:any[] = [];
	inRegionTime:string = '';//进入边界时间
	outRegionTime:string = '';//进入边界后离开时间
	myChart:any;//实例化折线图对象
	chartOption:any;//折线图配置
	xAxisData:any[] = [];//折线图X轴时间数据
	yAxisWeight:any[] = [];//重量折线数据
	yAxisSpeed:any[] = [];//速度折线数据
	//基本信息
	basInformation:any[] = [];
	timeOut:any;
	isDelete=false;
	loadPosition = null
	dischargePosition = null
	transformIcon = require('./icon/transform.png')
	areaData = []
	provinceNameArr = []
	cityNameArr = []
	townNameArr = []
	provinceNameArr1 = []
	cityNameArr1 = []
	townNameArr1 = []
	constructor(private jsonApiService: JsonApiService) {}

	ngOnInit() {
		this.selectDate()
		this.initBtn();
		this.initBaiduMap();//初始化地图
		this.boundaryRegion = new BMap.Boundary();//初始化一个行政边界区域构造器
		this.initDate().then(()=>{this.load()});
		this.selectCompany();
		this.getArea()
		// this.queryCarListByCompanyId().then(()=>this.selectCompany());
	}

	// 获取省市区，初始化级联选择器
	getArea() {
		this.jsonApiService.http("company/regionList.html", null).subscribe(res => {
			this.areaData = res.data;
			for(let item of this.areaData) {
				if(item.level === 2) {
					this.provinceNameArr.push(item);
					this.provinceNameArr1.push(item);
				}
			}
		})
	}

	provinceChange(e) {
		this.cityNameArr = [];
		this.townNameArr = [];
		this.queryForm.loadingAddressPId = e;
		this.queryForm.loadingAddressCId = ''
		this.queryForm.loadingAddressId = ''
		if (e !== '-1' && e !== '') {
			this.cityNameArr.push({areaName: '所有', id: '-1'})
		}
		for(let item of this.areaData) {
			if(this.queryForm.loadingAddressPId === item.parentId) {
				this.cityNameArr.push(item);
			}
		}
	}
	//城市change回调事件
	cityChange(e) {
		this.townNameArr = [];
		this.queryForm.loadingAddressCId = e;
		this.queryForm.loadingAddressId = ''
		if (e !== '-1' && e !== '') {
			this.townNameArr.push({areaName: '所有', id: '-1'})
		}
		for(let item of this.areaData) {
			if(this.queryForm.loadingAddressCId === item.parentId) {
				this.townNameArr.push(item);
			}
		}
	}
	townChange(e) {
		this.queryForm.loadingAddressId = e;
	}

	provinceChange1(e) {
		this.cityNameArr1 = [];
		this.townNameArr1 = [];
		this.queryForm.unloadAddressPId = e;
		this.queryForm.unloadAddressCId = ''
		this.queryForm.unloadAddressId = ''
		if (e !== '-1' && e !== '') {
			this.cityNameArr1.push({areaName: '所有', id: '-1'})
		}
		for(let item of this.areaData) {
			if(this.queryForm.unloadAddressPId === item.parentId) {
				this.cityNameArr1.push(item);
			}
		}
	}
	//城市change回调事件
	cityChange1(e) {
		this.townNameArr1 = [];
		this.queryForm.unloadAddressCId = e;
		this.queryForm.unloadAddressId = ''
		if (e !== '-1' && e !== '') {
			this.townNameArr1.push({areaName: '所有', id: '-1'})
		}
		for(let item of this.areaData) {
			if(this.queryForm.unloadAddressCId === item.parentId) {
				this.townNameArr1.push(item);
			}
		}
	}
	townChange1(e) {
		this.queryForm.unloadAddressId = e;
	}

	switchPosition() {
		this.queryForm.loadingAddressId = [this.queryForm.unloadAddressId, this.queryForm.unloadAddressId = this.queryForm.loadingAddressId][0]
		this.queryForm.loadingAddressCId = [this.queryForm.unloadAddressCId, this.queryForm.unloadAddressCId = this.queryForm.loadingAddressCId][0]
		this.queryForm.loadingAddressPId = [this.queryForm.unloadAddressPId, this.queryForm.unloadAddressPId = this.queryForm.loadingAddressPId][0]
		this.cityNameArr1 = [this.cityNameArr, [this.cityNameArr = this.cityNameArr1]][0]
		this.townNameArr1 = [this.townNameArr, [this.townNameArr = this.townNameArr1]][0]
	}

	deepClone(obj) {
		let objClone = Array.isArray(obj) ? [] : {};
		if (obj && typeof obj === "object") {
			for (let key in obj) {
				if (obj.hasOwnProperty(key)) {
					//判断ojb子元素是否为对象，如果是，递归复制
					if (key !== '__node') {
						if (obj[key] && typeof obj[key] === "object") {
							objClone[key] = this.deepClone(obj[key]);
						} else {
							//如果不是，简单复制
							objClone[key] = obj[key];
						}
					}
				}
			}
		}
		return objClone;
	}

	//判断是否有删除权限
	initBtn(){
		let btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_transportTask:listTask')));
		if(btnData){
			for(let item of btnData){
				if(item.sourceKey === "taskmanage:delete"&&item.parentId){
					this.isDelete = true;
				}
			}
		}
	}
	delete_row(row,e){
		e.stopPropagation();
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("transportTask/deleteTransportTask.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
	}
	ngOnDestroy(){
		clearTimeout(this.timeOut);
	}
	getTime(date){
		var year = date.getFullYear();
		var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
		var day = date.getDate()  < 10 ? "0" + date.getDate() : date.getDate();
		var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		return year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
	}
	//刷新
	refresh(){
		this.load();
	}
	//数据分类按钮点击事件
	btnClick(type){
		this.btnNum = type;
		this.curPage = 1;
		$('#popPage').animate({'width':0,'opacity':0},150);
		this.flag = false;
		this.load();
	}
	//初始化时间
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true
						}).on("changeDate", function(e){
							var date = e.date;
							var time = that.getTime(date);
							that.startTime=time;
							$("#datetimepicker2").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker2").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true
						}).on("changeDate", function(e){
							var date = e.date;
							var time = that.getTime(date);
							that.endTime=time;
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
						resolve();
					});
				}
			);
		})

	}
	//初始化车辆
	index = 1
	selectCompany(){
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				let sortList = []
				if (this.index === 1) {
					sortList = [
						{
							text: '装载重量',
							id: 'fullLoadWeight'
						}, {
							text: '进厂时间',
							id: 'emptyLoadTime'
						}, {
							text: '离场时间',
							id: 'fullLoadTime'
						}, {
							text: '卸货完成时间',
							id: 'unloadEndTime'
						}, {
							text: '装载耗时',
							id: 'loadingTime'
						}, {
							text: '卸载耗时',
							id: 'unloadingTime'
						}, {
							text: '运输时长',
							id: 'transportationTime'
						}, {
							text: '运输距离',
							id: 'transportationRange'
						}
					]
					$('#sortSelect').select2({
						language : "zh-CN",
						placeholder :"请选择",
						allowClear : true,
						data : sortList,//为Select添加数据
					}).on("select2:select", (e) => {
						this.queryForm.sortTypeNameArr = this.queryForm.sortTypeNameArr || []
						this.queryForm.sortTypeNameArr.push(e.params.data.id)
					}).on("select2:unselect", (e) => {
						const arrIndex = this.queryForm.sortTypeNameArr.indexOf(e.params.data.id)
						this.queryForm.sortTypeNameArr.splice(arrIndex, 1)
					})
					this.index++
				}
			})
	  	})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//清除车辆选中值
	del_carNumber(){
		this.deviceId = '';
		this.carNumber = '';
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberSelect2').val("");
		$("#select2-carNumberSelect2-container").empty();
		$("#select2-carNumberSelect2-container").attr("title","");
		$("#select2-carNumberSelect2-container").prepend(str);
	}
	//公司id拉取车辆
	queryCarListByCompanyId(){
		var that = this;
		return new Promise(function (resolve, reject){
			let reqdata = 'companyId=5c00ff008607352c75ab849e';
			that.jsonApiService.http("stats/carlist.html", reqdata).subscribe(data => {
				var carlist = data.data;
	        	var selectdata = [];
				if(data.success){
		        	for(var i = 0 ; i < carlist.length ; i++) {
		        		var obj = {id:carlist[i].deviceId,text:carlist[i].carNumber};
		        		selectdata[i] = obj;
		        	}
				}
				that.carList = selectdata;
				resolve();
			})
		})
	}
	//查询
	table_search(){
		this.curPage = 1;
		this.load();
	}
	loadSortData(){
		let reqdata = 'deviceId='+this.deviceId+'&startTime='+this.startTime+'&endTime='+this.endTime;
		this.jsonApiService.http("transportTask/countForTask.html", reqdata).subscribe(data => {
			if(data&&data.data){
				this.allData = data.data[0];
				this.normalData = data.data[1];
				this.abnormalData = data.data[2]
			}
		})
	}
	//初始地图
	initBaiduMap(){
		this.baiduMap= new BMap.Map('baiduMap',{enableMapClick: false}); //创建地图实例
		let point = new BMap.Point(117.7953288,28.2862345); //创建点坐标
		this.baiduMap.centerAndZoom(point, 12); //初始化地图，设置中心点坐标和地图级别
		this.baiduMap.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
	}
	initChart(){
		this.chartOption = {
		    title:{text: '重量曲线',left: 'center',textStyle:{fontSize:15}},
		    tooltip:{
		        trigger: 'axis',
		        axisPointer:{type: 'cross'},
		        formatter: function (params) {
		          	var paramIndex=params[0].dataIndex;
		          	var pointObj=this.trackData[paramIndex];
					if(!pointObj || pointObj.x == '' || pointObj.x == '0') {return};
					this.lineMoveCarPoint(pointObj)
		          	var res='';
		        	var len=params.length;
		        	for(var i=0;i<len;i++){
		        		res=res+params[i].marker+params[i].seriesName+':'+params[i].data+'</br>'
		        	}
		        	return res;
		        }.bind(this)
		    },
		    grid:{left: '48px',right: '36px',top:'60px',bottom:'24px'},
		    toolbox:{show: false},
			legend:{top:'20px'},
		    xAxis:{type: 'category',boundaryGap: false,data:[]},
		    yAxis:[{	
		    		name:'吨',
			        type: 'value',
			        axisLabel: {formatter: '{value}'},
			        axisPointer: {snap: true}
			    },{	
			    	name:'km/h',
		    		splitLine:{show:false},
			        type: 'value',
			        axisLabel: {formatter: '{value}'},
			        axisLine: {lineStyle: {color: '#5793f3'}},
			    }],
		    series: [
		        {
		            name:'重量',
		            type:'line',
		            smooth: true,
		            data:[],
		            markArea: {data: [ [{name: '',xAxis: '' },{xAxis: ''}]]}
		        },{
		            name:'速度',
		            type:'line',
		            smooth: true,
		            yAxisIndex: 1,
					data: [],
					itemStyle: {//样式
						normal: {color: '#5793f3',lineStyle: {width: 1,opacity: 0.5,}}
					},
					areaStyle: {//阴影
		                color: 'rgba(83, 146, 230,0.5)'
		            }
		        }
		    ]
		};
		this.myChart = echarts.init(document.getElementById('myChart'));
		this.myChart .setOption(this.chartOption, true);
		if(this.myChart){
			this.myChart.resize();
		}
		var that=this;
		$(window).resize(function (){
			//当浏览器大小变化时重新计算图表
		    that.myChart.resize();
		});
	}
	colsePop(){
		$('#popPage').animate({'width':0},150);
		this.flag = false;
	}
	isShow(){
		if(!this.flag){
			$('#popPage').animate({'width':"65%",'opacity':1},150);
			$("#popPage").height($(window).height()-60);
			this.flag = true;
		}else{
			$('#popPage').animate({'width':0,'opacity':0},150);
			this.flag = false;
		}
	}
	//初始化基本信息
	initBasInformation(){
		this.basInformation=[ 
			{name:'carNumber',value:'',textStr:'车牌'},
			{name:'fullLoadWeight',value:'',textStr:'净重'},
			{name:'loadingTime',value:'',textStr:'装载耗时'},
			{name:'transportationTime',value:'',textStr:'运输时长'},
			{name:'unloadingTime',value:'',textStr:'卸载耗时'},
			{name:'unloadEndTime',value:'',textStr:'卸货完成时间'},
			{name:'address',value:'',textStr:'卸货地址'}
		]
	}
	rowSelectEvent(row){
		this.activeSelected = row.id;
		var rowData=row;
		let timeDelay = 150;//设置动画时间
		if(!this.flag){
			$("#popPage").height($(window).height()-60);
			$('#popPage').animate({'width':'65%','opacity':1},timeDelay);
			this.flag = true;
		}
		this.initBasInformation();
		//清空地图轨迹
		clearTrackLine(this.baiduMap);
		this.baiduMap.closeInfoWindow();
		//清空行政区域
		this.baiduMap.removeOverlay(this.areaPly);
		this.baiduMap.removeOverlay(this.carMoveCanvasLayer);
		function nullUpdate() {}
		this.carMoveCanvasLayer = new CanvasLayer({//清空marker圆点
			map: this.baiduMap,
			update: nullUpdate,
			zIndex: 10
		});
		
		this.baiduMap.addOverlay(this.carMoveCanvasLayer);
		this.mapCantonName=rowData.unloadArea;
		this.mapCarNumber=row.carNumber;
		this.mapDeviceId=rowData.deviceId;
		let time1=common.getTimeMmss(new Date(common.mmsstoTimestamp(row.emptyLoadTime)-30*60*1000));//开始装货前半小时
		let time2=common.getTimeMmss(new Date(common.mmsstoTimestamp(row.unloadEndTime || row.lastDeviceTime || row.fullLoadTime)+30*60*1000));//卸货完成后半小时
		this.mapStartTime = time1;
		this.mapEndTime = time2;
		for (var i=0;i<this.basInformation.length;i++){
			var itemName=this.basInformation[i].name;
			this.basInformation[i].value = row[itemName] ? row[itemName] : '--'

		}
		if(this.flag){timeDelay = 0}
		this.timeOut = setTimeout(function(){
			this.askforData().then(()=>{
				this.initChart();//初始化折线图
				this.mapDeviceId = '';
				this.drawBoundary();
			});
		}.bind(this),timeDelay);
	}
	askforData(){
		return new Promise(function (resolve, reject) {
			this.trackData=[];
			this.xAxisData=[];
			this.yAxisWeight=[];
			this.yAxisSpeed=[];
			let reqdata = 'deviceId=' + this.mapDeviceId + '&startTime=' + this.mapStartTime + '&endTime=' + this.mapEndTime + '&showModify=' + false;
			this.jsonApiService.http("stats/draw.html", reqdata).subscribe(result => {
				var len = result.data.length;
				if(len<2){
					this.jsonApiService.message('该时间段没有数据...')
					return;
				}
				for(var i=0;i<len;i++){
					var mapPoint=toMapPoint(result.data[i]);
					if(mapPoint){
						this.trackData.push(mapPoint);
					}
					this.xAxisData.push(result.data[i].uploadDate);
					this.yAxisWeight.push(result.data[i].weight);
					this.yAxisSpeed.push(result.data[i].speed);
				}
				resolve();
			})
		}.bind(this))
	}
	//画轨迹图
	drawTrackLine(){
		var geturl=config.BaseURL;
		let lineStyle={star:true,end:false,color:true,infoUrl:geturl};
		drawTrackLine(this.trackData,this.baiduMap,lineStyle);
		
	}
	//绘画行政区域边界
	drawBoundary(){
    	var that=this;
    	if(that.mapCantonName==''||!that.mapCantonName){
    		this.drawChart();
    		this.drawTrackLine();
    		that.baiduMap.removeOverlay(that.areaPly);
    		var centerPoint=new BMap.Point(this.trackData[0].lng, this.trackData[0].lat);
    		that.baiduMap.centerAndZoom(centerPoint, 10);
    		return;
    	}
	    this.boundaryRegion.get(that.mapCantonName, function(rs){       //获取行政区域
	    	that.baiduMap.removeOverlay(that.areaPly);  //清除掉之前的边界区域
	        var count = rs.boundaries.length; //行政区域的点有多少个
	      	that.inRegionTime='';
      		that.outRegionTime='';
	      	if(count<1){
	        	return;
	        }
	        that.areaPly = new BMap.Polygon(rs.boundaries[0], {
	        	strokeColor:'blue',
						fillColor:'red',
						strokeWeight:1,
						strokeOpacity:0.2,
						fillOpacity:0.2
	        }); //建立多边形覆盖物
	        that.baiduMap.addOverlay(that.areaPly);  //添加覆盖物
	        that.baiduMap.setViewport(that.areaPly.getPath());    //调整视野  
	        that.drawTrackLine();
	        that.inTimeArr=[];
     		that.outTimeArr=[];
	     	function getInOutTimeArr(order){
	     		var isOut=false;//判断是否再进入边界后又再次出去
	     		var len=that.trackData.length;
     			for(var i=order;i<len;i++){
	        		var comparePoint=new BMap.Point(that.trackData[i].lng,that.trackData[i].lat);
			    	var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, that.areaPly);
			    	if (result){//在内部，把该点显示在地图上  
				      	that.inTimeArr.push(that.trackData[i].uploadDate);
				      	for(var j=i;j<len;j++){
							var comparePoint=new BMap.Point(that.trackData[j].lng,that.trackData[j].lat);
					    	var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, that.areaPly);
					    	if (!result) {//在内部，把该点显示在地图上  
					    		isOut=true;//判断是否再进入边界后又再次出去
						      	that.outTimeArr.push(that.trackData[j].uploadDate);
						      	if(j<len){
						      		getInOutTimeArr(j);
						      	}
							    break;   
							}
						}
				      	if(!isOut){
				    		that.outTimeArr.push(that.trackData[len-1].uploadDate);
				    	}
					    break;
					}  
	        	}
	     	}
	     	getInOutTimeArr(0);
			that.drawChart();
		})
	}
	//画折线图
	drawChart(){
		this.chartOption.xAxis.data=this.xAxisData;
		this.chartOption.series[0].data=this.yAxisWeight;
		this.chartOption.series[1].data=this.yAxisSpeed;
		var len=this.xAxisData.length;
		if(this.isEnter){
			var timeShadow=[];
			for(var i=0;i<this.inTimeArr.length;i++){
				var dataArr=[{
                    name: '进入特价区域',
                    xAxis: this.inTimeArr[i]
                },{
                	xAxis: this.outTimeArr[i]
           	 	}]
				timeShadow.push(dataArr)
			}
			this.chartOption.series[0].markArea.data= timeShadow;
		}
		this.myChart .setOption(this.chartOption, true);
		var that=this;
		this.myChart.on('click', function(params) {
			var pointObj= that.trackData[params.dataIndex];
			if(pointObj == undefined) {
				return;
			}
			
			var geturl=config.BaseURL;
			common.createInfoBox(that.baiduMap,pointObj,geturl);
			
		})
	}
	//折线移动,地图轨迹添加坐标位置点函数
	lineMoveCarPoint(data) {
		if(data.lat > 0) {
			var mp = this.baiduMap;
			var update = function update() {
				var ctx = this.canvas.getContext("2d");
				if(!ctx) {
					return;
				}
				ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
				var point = new BMap.Point(data.lng, data.lat);
				var pixel = mp.pointToPixel(point);
				ctx.beginPath();
				ctx.strokeStyle = '#d0d4d7';
				ctx.arc(pixel.x, pixel.y, 35, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = 'rgba(35, 152, 255, 0.14)';
				ctx.arc(pixel.x, pixel.y, 34, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.strokeStyle = '#c2c2c4';
				ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = '#fff';
				ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.fillStyle = '#1496ff';
				ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI);
				ctx.fill();
			};
			if(typeof this.carMoveCanvasLayer != 'undefined') {
				this.carMoveCanvasLayer.options.update = update;
				this.carMoveCanvasLayer._draw();
				return;
			}
			this.carMoveCanvasLayer = new CanvasLayer({
				map: this.baiduMap,
				update: update,
				zIndex: 10
			});
		}
	}
	//是否进入特价区域复选框变更事件
	isEnterChange(){
		var len=this.trackData.length;
		
		if(len<2){
			return
		}
		if(this.isEnter){
			var timeShadow=[];
			for(var i=0;i<this.inTimeArr.length;i++){
				var dataArr=[{
                    name: '进入特价区域',
                    xAxis: this.inTimeArr[i]
                },{
                	xAxis: this.outTimeArr[i]
           	 	}]
				timeShadow.push(dataArr)
			}
			this.chartOption.series[0].markArea.data= timeShadow;
		}
		else{
			this.chartOption.series[0].markArea= {
                data: [ [{
                    name: '',
                    xAxis: ''
                },{
                    xAxis: ''
                }]]
            }
			
		}
		this.myChart .setOption(this.chartOption, true);
	}
	//初始化加载list数据
	load(){
		this.activeSelected = '';
		if (!this.getQueryParam(false)) return
		let reqdata = 'gridPager=' + JSON.stringify(this.getQueryParam(false));
		this.jsonApiService.http("transportJob/transportJobList.html", reqdata).subscribe(data => {
			if(data&&data.exhibitDatas){
				for(let item of data.exhibitDatas){
					item.loadingTime = common.millisecond(item.loadingTime);
					item.unloadingTime = common.millisecond(item.unloadingTime);
					item.transportationTime = common.millisecond(item.transportationTime);
					item.transportationRange = (parseFloat(item.transportationRange) / 1000).toFixed(2)
				}
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}
		})
	}

	exportTable() {
		if (!this.getQueryParam(true)) return
		const param = this.getQueryParam(true)
		common.exprotDataFile(param, 'param', config.BaseURL + 'transportJob/transportJobListExport.html')
	}

	getQueryParam(isExport) {
		this.queryForm.startTime = $('#datetimepicker1').val()
		this.queryForm.endTime = $('#datetimepicker2').val()
		const timeCheck=common.correctTimeParams(this.queryForm.startTime,this.queryForm.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return false;
		}
		const param = {
			"pageSize": this.pageSize,
			"nowPage": this.curPage,
			"parameters": {
				...this.queryForm,
				startTransportation: this.queryForm.startTransportation || this.queryForm.startTransportation === 0 ? (parseFloat(this.queryForm.startTransportation) * 1000).toString() : '',
				endTransportation: this.queryForm.endTransportation || this.queryForm.endTransportation === 0 ? (parseFloat(this.queryForm.endTransportation) * 1000).toString() : '',
				sortTypeName: (this.queryForm.sortTypeNameArr || []).join(','),
				startTime: $('#datetimepicker1').val(),
				endTime: $('#datetimepicker2').val()
			}
		};

		if (this.queryForm.loadingAddressCId === '-1') {
			param.parameters.loadingAddressCId = ''
		} else if (this.queryForm.loadingAddressId === '-1') {
			param.parameters.loadingAddressPId = ''
			param.parameters.loadingAddressId = ''
		} else if (
			this.queryForm.loadingAddressId &&
			this.queryForm.loadingAddressId !== '-1'
		) {
			param.parameters.loadingAddressPId = ''
			param.parameters.loadingAddressCId = ''
		} else if (
			this.queryForm.loadingAddressId === '' &&
			this.queryForm.loadingAddressCId !== '-1' &&
			this.queryForm.loadingAddressCId
		) {
			param.parameters.loadingAddressPId = ''
		}

		if (this.queryForm.unloadAddressCId === '-1') {
			param.parameters.unloadAddressCId = ''
		} else if (this.queryForm.unloadAddressId === '-1') {
			param.parameters.unloadAddressPId = ''
			param.parameters.unloadAddressId = ''
		} else if (
			this.queryForm.unloadAddressId &&
			this.queryForm.unloadAddressId !== '-1'
		) {
			param.parameters.unloadAddressPId = ''
			param.parameters.unloadAddressCId = ''
		} else if (
			this.queryForm.unloadAddressId === '' &&
			this.queryForm.unloadAddressCId !== '-1' &&
			this.queryForm.unloadAddressCId
		) {
			param.parameters.unloadAddressPId = ''
		}


		delete param.parameters.sortTypeNameArr
		return isExport ? param.parameters : param
	}

	//删除所选时间
	del_date(){
		this.queryForm.startTime = '';
		this.queryForm.endTime ='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	delTransport() {
		this.queryForm.startTransportation = ''
		this.queryForm.endTransportation = ''
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	//删除
	deleteRow(row){
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(()=>{
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("stats/deletetransportdata.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}


	companySelected(data){
		this.queryForm.companyId = data.companyId;
		this.queryForm.deviceId = data.deviceId;
		this.queryForm.useTypeL2 = data.useTypeL2;
	}

	dateNumber:any = '10'; //查看天数
	specifyTime: any;
	selectDate() {
		if(!this.dateNumber){
			return
		}
		let nowTime = new Date();
		this.queryForm.endTime = common.getTimeMmss(nowTime);
		nowTime.setDate(nowTime.getDate() - this.dateNumber);
		this.queryForm.startTime = common.getTimeMmss(nowTime);
	}

	imgClose(dom) {
		dom.hide()
	}

	getStaticData(dom) {
		const param = this.getQueryParam(true)
		this.jsonApiService.http("transportJob/statisticsTransportJob.html", `param=${JSON.stringify(param)}`).subscribe(data => {
			this.statisticsForm = data.data
			dom.show()
		})
	}
}